package com.team407.cheyoubang.utils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.URL;
import java.security.MessageDigest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Paint;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.os.Handler;
import android.text.ClipboardManager;
import android.text.Html;
import android.text.Spanned;
import android.util.DisplayMetrics;
import android.util.Log;
import android.widget.Toast;
public class Utils {
	private static DisplayMetrics dm = null;
	public static int barHeight = 0;
	
	

	public static void initDisplayMetrics(Activity activity) {
		if (dm == null) {
			dm = new DisplayMetrics();
			activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		}
	}

	public static int pxToDip(int size){
		return (int) (size / dm.density + 0.5f);  
	}
	
	public static int dipToPx(int size){
		return (int) (size * dm.density + 0.5f);
	}
	
	@SuppressLint("CommitPrefEdits")
	public static void save(Context context, Map<String, String> map) {
		SharedPreferences preferences = context.getSharedPreferences(
				"data", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();
		Iterator<String> iterator = map.keySet().iterator();
		while (iterator.hasNext()) {
			String key = iterator.next();
			editor.putString(key, map.get(key));
		}
		editor.commit();
	}
	
	public static void save(Context context, String key, String value){
		SharedPreferences preferences = context.getSharedPreferences(
				"data", Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = preferences.edit();

		editor.putString(key, value);
		editor.commit();
	}
	
	public static String load(Context context, String key){
		SharedPreferences preferences = context.getSharedPreferences(
				"data", Context.MODE_PRIVATE);
		String value = preferences.getString(key, "");
		return value;
	}

	public static String[] load(Context context, String[] keys) {
		int size = keys.length;
		SharedPreferences preferences = context.getSharedPreferences(
				"data", Context.MODE_PRIVATE);
		String[] values = new String[size];
		for (int i = 0; i < size; i++) {
			values[i] = preferences.getString(keys[i], "");
		}
		return values;
	}
	
	
	public static DisplayMetrics getDisplayMetrics() {
		return dm;
	}


	public static boolean isEmpty(String string) {
		if (string == null || string.equals("")) {
			return true;
		} else {
			return false;
		}
	}

	public static int calculateInSampleSize(BitmapFactory.Options options,
			int reqWidth, int reqHeight) {
		// Raw height and width of image
		final int height = options.outHeight;
		final int width = options.outWidth;
		int inSampleSize = 1;

		if (height > reqHeight || width > reqWidth) {

			int inSampleSizeWith = Math.round((float) width / (float) reqWidth);
			int inSampleSizeHeight = Math.round((float) height
					/ (float) reqHeight);
			inSampleSize = Math.max(inSampleSizeWith, inSampleSizeHeight);
		}
		return inSampleSize;
	}

	public static Bitmap decodeSampledBitmapFromResource(String imagePath,
			int reqWidth, int reqHeight) {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(imagePath, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeFile(imagePath, options);
	}
	
	public static Bitmap decodeSampledBitmapFromUrl(String imageUrl,
			int reqWidth, int reqHeight) throws IOException {

		// First decode with inJustDecodeBounds=true to check dimensions
		final BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true;
		BitmapFactory.decodeStream(new URL(imageUrl).openStream(), null, options);

		// Calculate inSampleSize
		options.inSampleSize = calculateInSampleSize(options, reqWidth,
				reqHeight);

		// Decode bitmap with inSampleSize set
		options.inJustDecodeBounds = false;
		return BitmapFactory.decodeStream(new URL(imageUrl).openStream(), null, options);
	}

	public static String SpannedToString(Spanned spanned){
		String text = Html.toHtml(spanned);
		if(isEmpty(text)){
			return "";
		}else{
			StringBuffer out = new StringBuffer();
			unicodeToString(text, out);
			return out.toString();
		}
	}
	
	private static void unicodeToString(String text, StringBuffer out){
		Pattern pattern = Pattern.compile("\\&\\#(\\d+)\\;");
		Matcher matcher = pattern.matcher(text);
		int len = text.length();
		int start = 0;
		while(matcher.find()){
			int first = matcher.start();
			
			if(first > start){
				start = add(text, out, start, first);
			}
			
			char c = (char)Integer.parseInt(matcher.group(1));
			out.append(c);
			start = matcher.end();
		}
		if(start != len){
			start = add(text, out, start, len);
		}
	}
	
	private static int add(String text, StringBuffer out, int start, int end){
		String subString = text.substring(start, end);
		out.append(subString);
		return end;
	}
	
	
	
//	public static String saveImageCache(Bitmap cache,String fileName){
//		if(!fileName.endsWith(".jpg")){
//			fileName = fileName.substring(0,fileName.lastIndexOf(".")) + ".jpg";
//		}
//		File file = new File(Constant.IMAGE_CACHE_FILE, fileName);
//		if(cache != null){
//			FileOutputStream outputStream = null;
//			try {
//				outputStream = new FileOutputStream(file);
//				cache.compress(CompressFormat.JPEG, 100, outputStream);
//			} catch (FileNotFoundException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//		}
//		return file.getPath();
//	}
//	
	
	
	public static boolean isNetworkConn(Context context){
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
		NetworkInfo mobNetInfo = connectivityManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		boolean activeNetState = false;
		if (activeNetInfo != null) {
			if (activeNetInfo.getState() == State.CONNECTED) {
				activeNetState = true;
			}
		}
		boolean mobNetState = false;
		if (mobNetInfo != null) {
			if (mobNetInfo.getState() == State.CONNECTED) {
				mobNetState = true;
			}
		}
		return activeNetState||mobNetState;
	}
	
	public static Map<String, String> getUrlParam(String url){
		Map<String, String> params = new HashMap<String, String>();
		Pattern pattern = Pattern.compile("\\&?(\\w+)=(\\w+)\\&?");
		Matcher matcher = pattern.matcher(url);
		while(matcher.find()){
			String key = matcher.group(1);
			String value = matcher.group(2);
			params.put(key, value);
			
			Log.i("url--param", "key:" + key + "  value:" + value);
		}
		
		return params;
	}
	
	
	public static void MainToast(Handler handler,final Context context,final String text,final int duration){
		handler.post(new Runnable() {
			
			public void run() {
				Toast.makeText(context, text, duration).show();
			}
		});
	}
	
	
	
	public static void copy(Context context,String content){
		ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
		cmb.setText(content.trim());
	}
	
	public static void jumpToWlanSetting(Context context){
		Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
		context.startActivity(intent);
	}
	
	
	public static void getBarHeight(Context mContext){
		Class<?> c = null;
		Object obj = null;
		Field field = null;
		int x = 0;
		try {
		    c = Class.forName("com.android.internal.R$dimen");
		    obj = c.newInstance();
		    field = c.getField("status_bar_height");
		    x = Integer.parseInt(field.get(obj).toString());
		    barHeight = mContext.getResources().getDimensionPixelSize(x);
		} catch (Exception e1) {
		    e1.printStackTrace();
		} 
	}
	
	public static String getOrdersNo(long ulFlowNo, String strOrdersTime){
		return ulFlowNo + "`" + strOrdersTime;
	}
	
	public static Date StringToDate(String date){
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			return dateFormat.parse(date);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	
	/**
	* 将彩色图转换为黑白图
	* 
	* @param 位图
	* @return 返回转换好的位图
	*/
	public static Bitmap convertToBlackWhite(Bitmap bmp) {
		int width, height;
		height = bmp.getHeight();
		width = bmp.getWidth();
		Bitmap bmpGrayscale = Bitmap.createBitmap(width, height,
				Bitmap.Config.RGB_565);
		Canvas c = new Canvas(bmpGrayscale);
		Paint paint = new Paint();
		ColorMatrix cm = new ColorMatrix();
		cm.setSaturation(0);
		ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
		paint.setColorFilter(f);
		c.drawBitmap(bmp, 0, 0, paint);
		return bmpGrayscale;
	}
	/**
	 *  md5 加密
	 * @param s
	 * @return
	 */
	public final static String MD5(String s) {
        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};       
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
	}
}
